/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
/* eslint-disable @typescript-eslint/ban-types */
type Events = Record<string, Function[]>;

export class Bus {
  private events: Events

  constructor () {
    this.events = Object.create(null)
  }
  // 注册事件
  subscribe (type: string, fn: Function) {
    if (this.events[type]) {
      this.events[type].push(fn)
    } else {
      this.events[type] = [ fn ]
    }
  }
  // 发送事件
  post (type: string, ...args: any) {
    if (this.events[type]) {
      this.events[type].forEach((fn) => {
        // eslint-disable-next-line prefer-spread
        fn.apply(null, args)
      })
    }
  }
  // 取消订阅
  unsubscribe (type: string, fn: Function) {
    const cbs = this.events[type]
    // 如果传入的事件是数组, 循环解绑
    if (Array.isArray(type)) {
      for (let i = 0; i < type.length; i++) {
        this.unsubscribe(type[i], fn)
      }
    }
    // 如果传入的事件只有一个, 直接解绑
    if (cbs) {
      for (let i = 0; i < cbs.length; i++) {
        if (cbs[i] === fn) {
          this.events[type].splice(i, 1)
          break
        }
      }
    }
  }
}

export default { Bus }
